﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI.DataVisualization.Charting;
using SmsVotes.DataAccess;
using System.Drawing;
using System.IO;
using System.Web.SessionState;

namespace SmsVotes.ApplicationRuntime.Handlers
{
    public class ChartHandler : IHttpHandler, IRequiresSessionState
    {
        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return false; }
        }

        public void ProcessRequest(HttpContext context)
        {
            int stateID = int.Parse(context.Request.QueryString["sid"]);
            // Достаём состояние
            var currentState = StateManager.GetVoteStateByID(stateID);
            SmsServiceFacade.UpdateAnswersState(currentState);

            var currentQuestion = currentState.CurrentQuestion;
            if (currentState.Ended && !String.IsNullOrEmpty(context.Request.QueryString["qid"]))
            {
                var questionID = int.Parse(context.Request.QueryString["qid"]);
                currentQuestion = QuestionManager.GetByID(questionID);
            }
            // Заполняем заголовок графика
            var title = new Title(currentQuestion.Name, Docking.Top, new Font(FontFamily.GenericSerif, 14), Color.Black);
            System.Web.UI.DataVisualization.Charting.Chart cResults = new System.Web.UI.DataVisualization.Charting.Chart();

            cResults.ChartAreas.Add(new ChartArea("caResults") { Area3DStyle = new ChartArea3DStyle() });
            cResults.Titles.Add(title);
            int totalVotes = 0;//Всего голосов
            var series = new Series();
            // Определяем тип графика и создаём легенду для кругового графика
            if (currentQuestion.Chart.ID == 1)
                series.ChartType = SeriesChartType.Column;
            if (currentQuestion.Chart.ID == 2)
            {
                series.ChartType = SeriesChartType.Pie;
                var legend = new Legend();
                series.Legend = legend.Name;
                cResults.Legends.Add(legend);

            }
            // загружаем ответы
            currentQuestion.Answers.SmartLoad(currentQuestion);
            foreach (var answer in currentQuestion.Answers)
            {
                var nVotes = (from item in answer.AnswerStates
                              where item.VoteState.ID == stateID
                              select item.Votes).FirstOrDefault();
                totalVotes += nVotes;
                var point = new DataPoint();
                point.LegendText = answer.Name;
                point.SetValueY(nVotes);
                if (currentQuestion.Chart.ID == 1)
                    point.Label = answer.Name;
                if (currentQuestion.Chart.ID == 2)
                {
                    point.Label = nVotes.ToString();
                }
                series.Points.Add(point);

            }
            cResults.Series.Add(series);


            context.Response.ContentType = "image/png";
            context.Response.Charset = "";
            var imageStream = new MemoryStream();
            cResults.SaveImage(imageStream);
            context.Response.BinaryWrite(imageStream.GetBuffer());
        }

        #endregion
    }
}
